<template>
  <div class="upload-container">
    <el-button :style="{background:color,borderColor:color}" icon="el-icon-upload" size="mini" type="primary" @click=" dialogVisible=true">
      上传图片
    </el-button>
    <el-dialog title="上传图片" class="upload-container-dialog" append-to-body width="560px" :visible.sync="dialogVisible">
      <el-alert
        title="严禁上传违规违法/色情色诱/低俗/广告等图片内容，违者下架对应内容并封号处理"
        type="warning"
        :closable="false"
        show-icon>
      </el-alert>
      <el-upload
        :multiple="true"
        :file-list="fileList"
        :show-file-list="true"
        :on-remove="handleRemove"
        :data="addData"
        :on-success="handleSuccess"
        accept="image/png,image/jpeg,image/jpg,image/gif"
        :on-error="errorFn"
        :before-upload="beforeUpload"
        class="editor-slide-upload"
        :action="action"
        list-type="picture-card"
      >
        <el-button size="small" type="primary">
          点击上传
        </el-button>
      </el-upload>

      <p class="upload-container-tips">温馨提示：当前图片上传仅支持png、jpg、jpeg、gif格式，图片大小不超过{{size}}MB</p>
      <div slot="footer" style="text-align: right">
        <el-button  size="small" @click="dialogVisible = false">
          取消
        </el-button>
        <el-button  size="small" type="primary" @click="handleSubmit">
          确认
        </el-button>
      </div>

    </el-dialog>
  </div>
</template>

<script>
// import { getToken } from 'api/qiniu'

export default {
  name: 'EditorSlideUpload',
  props: {
    color: {
      type: String,
      default: '#1890ff',
    },
  },
  data() {
    return {
      size:5,
      dialogVisible: false,
      action: this._IMG_POST_URL, // https://httpbin.org/post
      // action: "https://httpbin.org/post", // https://httpbin.org/post
      listObj: {},
      fileList: [],
      userInfo:{},
      addData:{
        akey:"892199f69336cfad9ba22996a79c8f05",
        token:""
      }
    };
  },
  created(){
    this.userInfo = this._storage.get(this._userKey);
    this.addData.token = this.userInfo.token
  },
  methods: {
    beforeUpload1(file){
      // 文件上传时的钩子
      console.log(file);
      const typeList = "/png|/jpeg|/jpg|/gif";
      const fileType = file.type;
      const type = fileType.substring(fileType.lastIndexOf("/")).toLowerCase();
      const isJPG = typeList.indexOf(type) === -1;
      const isLt2M = file.size / 1024 / 1024 < this.size;
      if (isJPG) {
        this.$message.error("上传的图片只能是jpeg/jpg/png/gif格式!");
      }
      if (!isLt2M) {
        this.$message.error(`上传图片大小不能超过 ${this.size}MB!`);
      }
      if (!isJPG && isLt2M) {
        this.upLoading = true;
      }
      return !isJPG && isLt2M;
    },
    successFn(res) {
      // 文件上传成功时的钩子
      if (res.rcode === "2") {
        this.upLoading = false;
        const info = res[this.addReturnKey][0];
        const data = {
          img_http: info.img_http,
          imgsp_ty: info.img_do, // 通用
          imgsp_id: info.img_id,
          imgsp_ty_s: info.img_do_s,
          imgsp_pc01: "",
          imgsp_pc01_s: "",
          imgsp_pc02: "",
          imgsp_pc02_s: "",
          imgsp_pc03: "",
          imgsp_pc03_s: "",
          imgsp_pc04: "",
          imgsp_pc04_s: "",
          imgsp_pc0x: "",
          imgsp_pc0x_s: "",
          imgsp_app01: "",
          imgsp_app01_s: "",
          imgsp_app02: "",
          imgsp_app02_s: "",
          imgsp_app03: "",
          imgsp_app03_s: "",
          imgsp_app04: "",
          imgsp_app04_s: "",
          imgsp_app0x: "",
          imgsp_app0x_s: "",
          imgsp_td01: "",
          imgsp_td01_s: "",
          imgsp_td02: "",
          imgsp_td02_s: "",
          imgsp_td03: "",
          imgsp_td03_s: ""
        };
        this.imgurl_list.push(data);
      } else {
        this.upLoading = false;
        this.$message.error(`上传失败! ${res.rmsg}`);
      }
    },
    beforeUpload(file) {
      // 文件上传时的钩子
      console.log(file);
      const typeList = "/png|/jpeg|/jpg|/gif";
      const fileType = file.type;
      const type = fileType.substring(fileType.lastIndexOf("/")).toLowerCase();
      const isJPG = typeList.indexOf(type) === -1;
      const isLt2M = file.size / 1024 / 1024 < 5;
      if (isJPG) {
        this.$message.error("上传的图片只能是jpeg/jpg/png/gif格式!");
      }
      if (!isLt2M) {
        this.$message.error(`上传图片大小不能超过 ${this.size}MB!`);
      }
      if (isJPG || !isLt2M) {
        return false
      }
      const _self = this;
      const _URL = window.URL || window.webkitURL;
      const fileName = file.uid;

      this.listObj[fileName] = {};
      return new Promise((resolve, reject) => {
        const img = new Image();

        img.src = _URL.createObjectURL(file);
        img.onload = function () {
          _self.listObj[fileName] = {
            hasSuccess: false, uid: file.uid, width: this.width, height: this.height,
          };
        };
        resolve(true);
      });
    },
    checkAllSuccess() {
      return Object.keys(this.listObj).every((item) => this.listObj[item].hasSuccess);
    },
    handleSubmit() {
      const arr = Object.keys(this.listObj).map((v) => this.listObj[v]);

      if (!this.checkAllSuccess()) {
        this.$message.warning("请等待所有图片上传成功。如果出现网络问题，请刷新页面并重新上传！");
        return;
      }
      this.$emit('successCBK', arr);
      this.listObj = {};
      this.fileList = [];
      this.dialogVisible = false;
    },
    handleSuccess(response, file,fileList) {
      if (response.rcode === '2') {
        const { uid } = file;
        const objKeyArr = Object.keys(this.listObj);

        for (let i = 0, len = objKeyArr.length; i < len; i++) {
          if (this.listObj[objKeyArr[i]].uid == uid) {
            this.listObj[objKeyArr[i]].url = this._TEMP_URL + response.file_url.okAllFileName;
            // this.listObj[objKeyArr[i]].url = response.files.file;
            this.listObj[objKeyArr[i]].hasSuccess = true;
            break;
          }
        }
      }else {
        this.$message.error(`上传失败! ${response.rmsg}`);
        this.handleRemove(file,fileList)
      }
    },
    errorFn(err, file,fileList){
      this.handleRemove(file,fileList);
      console.log(err);
      this.$message.error("服务器出错，上传失败!");
    },
    handleRemove(file,fileList) {
      const { uid } = file;
      const objKeyArr = Object.keys(this.listObj);
      console.log(file,fileList,this.listObj)
      for (let i = 0, len = objKeyArr.length; i < len; i++) {
        if (objKeyArr[i] == uid) {
          console.log(objKeyArr,objKeyArr[i],uid)
          delete this.listObj[objKeyArr[i]];
          // fileList.splice(i,1)
          break;
        }
      }
    },


  },
};
</script>

<style lang="scss" scoped>
  .upload-container-dialog{
    &::v-deep .el-dialog__body{
      padding: 10px;
    }
  }
.editor-slide-upload {
  margin-top: 10px;
}
  .upload-container-tips{
    margin-top: 5px;
    font-size: 12px;
    color: #999999;
  }
</style>
